/*
todo:
- my grafic card or ps 3.0 has an iteration limit it seams. So when there are more steps needed the shader breaks up.
- and the quality can be better. step size is 0.005. but at 256^3 in full diagonal is would be needed to 0.00225. and 256^3 is not the biggest volume
- insert clipping. also when there is none from the user because the textures are bigger than the object so clip it too save performance
- make step size volume depedant for full quality
- make step size view direction dependand for performance
*/

uniform sampler3D volumeTexture;
uniform sampler1D transferTexture;
uniform sampler2D frontTexture;
uniform sampler2D backTexture;
uniform sampler2D colorTexture;
uniform float stepDist;
uniform int startStep;

void main()
{
	//gl_FragColor = texture2D(frontTexture, gl_TexCoord[0].st);
	//gl_FragColor = abs(texture2D(frontTexture, gl_TexCoord[0].st) - texture2D(backTexture, gl_TexCoord[0].st));

	vec4 startPoint = texture2D(frontTexture, gl_TexCoord[0].st);

	if(startPoint.w == 0.0)
	{
		discard;
	}
	else
	{
		vec4 endPoint = texture2D(backTexture, gl_TexCoord[0].st);
		float maxIntensity = texture2D(colorTexture, gl_TexCoord[0].st).w;
		//float iterDist = distance(startPoint, endPoint) / stepDist;
		//vec3 iterDiff = (endPoint.xyz - startPoint.xyz) / iterDist;
		vec3 iterDiff = (endPoint.xyz - startPoint.xyz) * stepDist;

		vec3 currPoint = startPoint.xyz + iterDiff * startStep;
		//int maxIter = int(distance(startPoint, endPoint) / stepDist) - startStep;
		//if(maxIter < 0)discard;

		for(int i = 0;i < #;i++)
		{
			float tmpIntensity = texture3D(volumeTexture, currPoint).x;
			//float tmpIntensity = texture3D(volumeTexture, currPoint).x;

			maxIntensity = max(tmpIntensity, maxIntensity);
			currPoint += iterDiff;
			//if(i >= maxIter)break;
			//currPoint = startPoint.xyz + iterDiff * (startStep + i);
		}
		
		gl_FragColor = texture1D(transferTexture, clamp(maxIntensity, 0.0, 0.999));
		gl_FragColor.xyz = gl_FragColor.xyz * gl_FragColor.a;
		//gl_FragColor = vec4(maxIntensity, maxIntensity , maxIntensity, 0);
	}
}